package com.dinadi.yidi.ui.fragment;

import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.WatchingAdapter;
import com.dinadi.yidi.base.BaseFragment;
import com.dinadi.yidi.bean.CreativeHotspotRequestEntity;
import com.dinadi.yidi.bean.CreativeProductRequest;
import com.dinadi.yidi.bean.ListBean;
import com.dinadi.yidi.bean.ShareBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.activity.ClassificationActivity;
import com.dinadi.yidi.ui.activity.CreativeHotspotDetailsActivity;
import com.dinadi.yidi.ui.activity.ExhibitionMatchActivity;
import com.dinadi.yidi.ui.activity.ProductDetailsActivity;
import com.dinadi.yidi.ui.activity.ProductSubjectAllActivity;
import com.dinadi.yidi.ui.activity.SearchExhibitionActivity;
import com.dinadi.yidi.ui.view.FlyBanner;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.pullloadmorerecyclerview.PullLoadMoreRecyclerView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2018/4/25   首页-看点（新 改版）
 * Time: 10:29
 */

public class WatchingFragment extends BaseFragment {
    private View view;
    private ImageView exhibition_icon_search;
    private PullLoadMoreRecyclerView mPullLoadMoreRecyclerView;
    private WatchingAdapter mRefreshAdapter;
    private FlyBanner banner;
    private String token;
    private String lastId = "";
    private List<String> picList;//bananert图片
    private List<Integer> picLocalList;//bananert本地图片
    private ListBean bannerBean;
    private List<CreativeHotspotRequestEntity> dataList = new ArrayList<>();

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_watching, null);
        return view;
    }

    @Override
    protected void initView() {
        changePager(2);
        banner = (FlyBanner) view.findViewById(R.id.banner);
        exhibition_icon_search = (ImageView) view.findViewById(R.id.exhibition_icon_search);
        mPullLoadMoreRecyclerView = (PullLoadMoreRecyclerView) view.findViewById(R.id.pullLoadMoreRecyclerView);
        mPullLoadMoreRecyclerView.setGridLayout(1);
        mRefreshAdapter = new WatchingAdapter(getActivity());
        mPullLoadMoreRecyclerView.setAdapter(mRefreshAdapter);
        mPullLoadMoreRecyclerView.setOnPullLoadMoreListener(new PullLoadMoreListener());
        mPullLoadMoreRecyclerView.setPullRefreshEnable(false);
        MobclickAgent.onEvent(getActivity(), "Watching", "看点tab");
    }

    @Override
    protected void initListener() {
        registerClickListener(exhibition_icon_search);
        banner.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String targetUrl = bannerBean.getBannerList().get(position).getTargetUrl();
                String type = targetUrl.substring(0, targetUrl.lastIndexOf("="));
                String id = targetUrl.substring(targetUrl.lastIndexOf("=") + 1);
                if (type.equals("http://YiDi_ProductDetail_ProductId")) {
                    /*商品详情*/
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                    intent.putExtra("productId", id);
                    startActivity(intent);
                } else if (type.equals("http://YiDi_ProductList_ProductListId")) {
                    /*商品列表*/
                    Intent intent = new Intent(getActivity(), ProductSubjectAllActivity.class);
                    intent.putExtra("proSubId", id);
                    startActivity(intent);

                } else if (type.equals("http://YiDi_GameDetail_GameDetailId")) {
                    /*活动详情*/
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), ExhibitionMatchActivity.class);
                    intent.putExtra("showId", id);
                    startActivity(intent);
                } else if (type.equals("http://YiDi_ArticleDetail_ArticelDetail")) {
                    /*创意热点 文章详情*/
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), CreativeHotspotDetailsActivity.class);
                    intent.putExtra("hotId", id);
                    startActivity(intent);
                } else if (type.equals("http://YiDi_DesignerDetail_DesignerDetailId")) {
                    /*设计师详情id 设计师详情*/
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), CreativeHotspotDetailsActivity.class);
                    intent.putExtra("dUserId", id);
                    startActivity(intent);
                }
            }
        });


    }

    @Override
    protected void clickEvent(View v) {

        switch (v.getId()) {
            case R.id.exhibition_icon_search:
                /*搜索*/
                Intent searchIntent = new Intent(getActivity(), SearchExhibitionActivity.class);
                searchIntent.putExtra("type", "2");
                startActivity(searchIntent);
                MobclickAgent.onEvent(getActivity(), "WatchingSearch", "看点搜索");
                break;
            default:
                break;
        }
    }

    @Override
    protected void initData() {
        token = SharePreferencesHelper.getInstance(getActivity()).getString("token");
        showLoadingDialog(getResources().getString(R.string.dialog_text));
        /*获取banner*/
        obtainBanner();
        initPullrefresh();

    }

    /*获取banner*/
    private void obtainBanner() {
        ShareBean bean = new ShareBean();
        bean.setToken(token);
        bean.setType("2");
        CommonInterface messageInterface = new CommonInterface(getActivity(), bannerListener);
        messageInterface.getInterface("13006", JSON.toJSONString(bean));
        picList = new ArrayList<>();
        picLocalList = new ArrayList<>();
    }

    /*bannner*/
    HttpListener bannerListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                bannerBean = JsonUtil.parseJsonToBean(response, ListBean.class);
                if (bannerBean.getBannerList().size() == 0) {
                    picLocalList.add(R.drawable.symbols_bitmap);
                    banner.setImages(picLocalList);
                    banner.setOnItemClickListener(null);
                } else {
                    for (int i = 0; i < bannerBean.getBannerList().size(); i++) {
                        picList.add(bannerBean.getBannerList().get(i).getImgUrl());
                    }
                    banner.setImagesUrl(picList);
                }


            } else {
                toast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    HttpListener httpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            closeLoadingDialog();
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                CreativeProductRequest bean = JsonUtil.parseJsonToBean(response, CreativeProductRequest.class);
                dataList = bean.getArticleList();

                mRefreshAdapter.addAllData(dataList);
                getData();


            } else {
                closeLoadingDialog();
                toast(errMsg);
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            toast("加载失败");
        }
    };

    private void getData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                //刷新结束
                mPullLoadMoreRecyclerView.setPullLoadMoreCompleted();
            }
        }, 1000);
    }


    class PullLoadMoreListener implements PullLoadMoreRecyclerView.PullLoadMoreListener {
        @Override
        public void onRefresh() {
            setRefresh();
        }

        @Override
        public void onLoadMore() {
            //page = page + 1;
            lastId = dataList.get(dataList.size() - 1).getHotId();
            initPullrefresh();
        }
    }

    private void setRefresh() {
        mRefreshAdapter.clearData();
        //page = 1;
        initPullrefresh();
    }

    private void initPullrefresh() {
        ShareBean bean = new ShareBean();
        bean.setLastId(lastId);
        bean.setToken(token);
        bean.setPageSize("10");
        CommonInterface creativeProductInterface = new CommonInterface(getActivity(), httpListener);
        creativeProductInterface.getInterface("12011", JSON.toJSONString(bean));
    }
}
